package com.ce.webframework.sec.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.util.BlankUtil;
import com.ce.webframework.sec.model.SecExcludeSchedDO;
import com.ce.webframework.sec.model.SecScheduleDO;
import com.ce.webframework.sec.service.ISecDictService;
import com.ce.webframework.sec.service.ISecScheduleService;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;

public class SecScheduleAction extends PmsBaseAction {

	// 字典
	private ISecDictService secDictService;

	private ISecScheduleService secScheduleService;

	public void setSecScheduleService(ISecScheduleService secScheduleService) {
		this.secScheduleService = secScheduleService;
	}

	/**
	 * 功能描述:初始化字典下拉
	 *
	 *
	 */

	public void getSysCalDict() {
		// 提醒周期
		this.getRequest().setAttribute("reminderCycleList",	secDictService.getSecDictList("reminder_cycle"));

		// 重复周期
		this.getRequest().setAttribute("repeatCycleList", secDictService.getSecDictList("repeat_cycle"));

	}

	/**
	 * 功能描述:根据用户Id和日期 查找 SecScheduleDO对象列表
	 *
	 * @param selectedDate
	 *            当前选择的日期
	 * @return List<SecScheduleDO> 对象
	 *
	 * 返回符合条件的查询对象列表
	 */

	public List<SecScheduleDO> getSecScheduleList(Date selectedDate, HttpServletRequest request) {
//		ResUserVO user = (ResUserVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return secScheduleService.getSecScheduleList(getLoginUser(request).getUserId(), selectedDate);
	}

	/**
	 * 功能描述:增加日程记录
	 *
	 * @param schDO
	 *            SecScheduleDO 实体对象
	 * @return void
	 * @throws IOException
	 * @throws ServletException
	 */

	public void addSecSchedule(@Read(key = "title") String title, @Read(key = "contentweb")
								String content, @Read(key = "repeatCycle")
								String repeatCycle, @Read(key = "reminderCycle")
								String remindCycle, @Read(key = "beginDate")
								String beginDate, @Read(key = "endUpDate")
								String endUpDate) throws ServletException, IOException {

//		SimpleDateFormat parseBeginDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//		SimpleDateFormat parseEndDate = new SimpleDateFormat("yyyy-MM-dd");
//
//		Date startDate = null;
//		Date endDate = null;
//		if (beginDate != "" && beginDate != null) {
//			try {
//				startDate = parseBeginDate.parse(beginDate);
//
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}
//		}
//
//		if (repeatCycle.equals("31")) {
//			endDate = startDate;
//		}
//
//		if (!(repeatCycle.equals("31")) && endUpDate != "" && endUpDate != null) {
//			try {
//				endDate = parseEndDate.parse(endUpDate);
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}
//		}
//
//		SecScheduleDO schDO = new SecScheduleDO();
//		schDO.setTitle(title);
//		schDO.setContent(content);
//		schDO.setRemindCycle(remindCycle);
//		schDO.setRepeatCycle(repeatCycle);
//		schDO.setStartTime(startDate);
//		schDO.setEndTime(endDate);
//
//		// schDO.setUserId((String)this.getRequest().getAttribute("userId"));
//		// ResUserVO user =
//		// (ResUserVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		schDO.setUserId(getLoginUser().getUserId());
//		// schDO.setEpId((String)this.getRequest().getAttribute("epId"));
//		schDO.setEpId(getLoginUser().getEpId());
//		SecScheduleDO returnSchDO = secScheduleService.addSecSchedule(schDO);
//		SecScheduleDO reminderSchDO = this.tackleReminderTime(returnSchDO);
//		this.getRequest().setAttribute("scheduleId",returnSchDO.getScheduleId());
//		// this.getRequest().getRequestDispatcher("CryptoData.jsp").(request,response);
//
//		System.out.println(" scheduleId abc==" + this.getRequest().getAttribute("scheduleId"));
//		String hasValue = "fail";
//		if (reminderSchDO != null) {
//			hasValue = "correct";
//		}
//		this.getRequest().setAttribute("hasValue", hasValue);
//
//		this.getSysCalDict();
//		RequestDispatcher rd = this.getRequest().getRequestDispatcher("pages/webframework/sec/Aux_worktable_msg_add.jsp");
//		// Forward to requested URL
//		rd.forward(this.getRequest(), this.getResponse());
		// return "worktable";
	}



	/**
	 * 功能描述:按主键Id 删除日程记录
	 *
	 * @param scheduleId
	 *            SecScheduleDO 的主键
	 * @param delType
	 *            删除类型的类型
	 * @param delDate
	 *            删除日期
	 * @return boolean 删除成功是为true，失败时为false
	 */

	public boolean deleteSecSchedule(String scheduleId, String delType,	Date delDate) {
		System.out.println(" scheduleId  del"+scheduleId);
		boolean returnState = false;
		// 此系列活动的所有活动
		Long scheduId = Long.valueOf(scheduleId);
		if (delType.equals("all")) {
			secScheduleService.delSecExcludeSchedDO(scheduId);
			returnState = secScheduleService.deleteSecSchedule(scheduId);
		}

		// 仅此活动
		if (delType.equals("thisOneOnly")) {
			System.out.println("thisOneOnly  "+scheduleId);
			// 新增加一条记录到 日历删除修改表
			SecExcludeSchedDO excludeDO = new SecExcludeSchedDO();
			SecScheduleDO schDO = secScheduleService.getSecScheduleById(scheduId);
			System.out.println("thisOneOnly  "+schDO.getScheduleId());
			excludeDO.setEpId(schDO.getEpId());
			excludeDO.setExcludeDate(delDate);
			excludeDO.setSecSchedule(schDO);
			excludeDO.setUserId(schDO.getUserId());
			secScheduleService.addSecExcludeSchedDO(excludeDO);
			returnState = true;
		}
		return returnState;
	}

	/**
	 * 功能描述:根据scheduleId查找SecScheduleDO对象
	 *
	 * @param scheduleId
	 *            SecScheduleDO对象的Id
	 * @return SecScheduleDO id对应的SecScheduleDO对象
	 */
	@Out(key = "secScheduleDO")
	public SecScheduleDO getSecScheduleById(@Read(key = "scheduleId") String scheduleId) {

		// 提醒周期
		this.getRequest().setAttribute("reminderCycleList", secDictService.getSecDictList("reminder_cycle"));
		// 重复周期
		this.getRequest().setAttribute("repeatCycleList", secDictService.getSecDictList("repeat_cycle"));
		Long scheduId = Long.valueOf(scheduleId);
		SecScheduleDO secSchObj=secScheduleService.getSecScheduleById(scheduId);
//		this.getRequest().setAttribute("repeatCycle",secSchObj.getRepeatCycle());
		return secSchObj;
	}

	/**
	 * 功能描述:根据scheduleId查找SecScheduleDO对象
	 *
	 * @param scheduleId
	 *            SecScheduleDO对象的Id
	 * @return void
	 */
	public void getSecScheduleXmlById(@Read(key = "scheduleId") String scheduleId) {

		SecScheduleDO returnSchDO= secScheduleService.getSecScheduleById(Long.valueOf(scheduleId));
		SecScheduleDO reminderSchDO = this.tackleReminderTime(returnSchDO);
		if(!BlankUtil.isBlank(reminderSchDO)){
			StringBuffer buffer = new StringBuffer();
			buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			buffer.append("<msg-list>");
			buffer.append("<msg>");
			buffer.append("<id>" + reminderSchDO.getScheduleId() + "</id>");
			buffer.append("<timeOut>" + reminderSchDO.getTimeGap() + "</timeOut>");
			buffer.append("<title>" + reminderSchDO.getTitle() + "</title>");
			buffer.append("<time>" + reminderSchDO.getStartTimeFormat() + "</time>");
			buffer.append("<detail>" + reminderSchDO.getContent() + "</detail>");
			buffer.append("<repeat>" + reminderSchDO.getRepeatCycle() + "</repeat>");
			buffer.append("<remind>" + reminderSchDO.getRemindCycle() + "</remind>");
			buffer.append("</msg>");
			buffer.append("</msg-list>");
			String returnValue = buffer.toString();
			System.out.println(" returnValue ="+returnValue);
			this.renderXML(returnValue);
		}
	}

	/**
	 * 功能描述:更新日程记录
	 *
	 * @param calDO
	 *            SecScheduleDO 实体对象
	 * @return void 增加后的对象
	 */

	public void updateSecSchedule(@Read(key = "scheduleId")String scheduleId,
									@Read(key = "title") String title,
									@Read(key = "content")String content,
									@Read(key = "startTimeDate")String startTimeDate,
									@Read(key = "startTimeHour")String startTimeHour,
									@Read(key = "repeatCycle")String repeatCycle,
									@Read(key = "remindCycle")String remindCycle,
									@Read(key = "endUpDate") String endUpDate,
									@Read(key = "modifyTypeName")String modifyType) {

		SecScheduleDO schDO = secScheduleService.getSecScheduleById(Long.valueOf(scheduleId));

		SimpleDateFormat parseBeginDate = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		SimpleDateFormat parseEndDate = new SimpleDateFormat("yyyy-MM-dd");
		Date startTime = null;
		Date endTime = null;

		if (startTimeDate != "" && startTimeDate != null) {
			try {
				startTime = parseBeginDate.parse(startTimeDate+" "+startTimeHour);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		if(repeatCycle.equals("31")){
			endTime=startTime;
		}
		if (!(repeatCycle.equals("31"))&&endUpDate != "" && endUpDate != null) {
			try {
				endTime = parseEndDate.parse(endUpDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		SecScheduleDO reminderSchDO = null;
		String updateTypeValue="";

		// 此系列活动的所有活动
		if (modifyType.equals("all")) {
			schDO.setStartTime(startTime);
			schDO.setEndTime(endTime);
			schDO.setTitle(title);
			schDO.setRepeatCycle(repeatCycle);
			schDO.setRemindCycle(remindCycle);
			schDO.setContent(content);
			SecScheduleDO returnSchDO = secScheduleService.updateSecSchedule(schDO);
			updateTypeValue="all";
			reminderSchDO = this.tackleReminderTime(returnSchDO);
		}

		// 仅此活动
		if (modifyType.equals("thisOneOnly")) {
			// 新增加一条记录到 日历删除修改表
			Date delTime = null;
			if (startTimeDate != "" && startTimeDate != null) {
				try {
					delTime = parseEndDate.parse(startTimeDate);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}

			SecScheduleDO newSchDO = new SecScheduleDO();
			newSchDO.setTitle(title);
			newSchDO.setContent(content);
			newSchDO.setCreateTime(new Date());
			newSchDO.setEpId(schDO.getEpId());
			newSchDO.setEndTime(endTime);
			newSchDO.setStartTime(startTime);
			newSchDO.setUserId(schDO.getUserId());
			newSchDO.setRepeatCycle(repeatCycle);
			newSchDO.setRemindCycle(remindCycle);
			SecScheduleDO returnSchDO = secScheduleService.addSecSchedule(newSchDO);
			reminderSchDO = this.tackleReminderTime(returnSchDO);
			// 原来排除记录的scheduleId
//			reminderSchDO.setScheduleIdTemp(scheduleId);
			SecExcludeSchedDO excludeDO = new SecExcludeSchedDO();
			excludeDO.setEpId(schDO.getEpId());
			excludeDO.setExcludeDate(delTime);
			excludeDO.setSecSchedule(schDO);
			excludeDO.setUserId(schDO.getUserId());
			secScheduleService.addSecExcludeSchedDO(excludeDO);
			updateTypeValue="thisOneOnly";
		}

		String hasUpdateValue="fail";
		Long newScheduleId=1l;
		if(reminderSchDO!=null){
			hasUpdateValue="correct";
			newScheduleId=reminderSchDO.getScheduleId();
		}
		this.getRequest().setAttribute("updateType",updateTypeValue);
		this.getRequest().setAttribute("hasUpdateValue",hasUpdateValue);
		this.getRequest().setAttribute("newScheduleId",newScheduleId);
		this.getRequest().setAttribute("oldScheduleId",scheduleId);
		this.getSysCalDict();
        RequestDispatcher rd = this.getRequest().getRequestDispatcher("pages/webframework/sec/Aux_worktable_msg_bj.jsp");
        //Forward to requested URL
        try {
			rd.forward(this.getRequest(), this.getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 当改变月份时调用此方法，取得下个月的需要改变样式的天
	 *
	 * @param yy
	 * @param mm
	 */
	public int[] changeMonthStyle(String yy, String mm, HttpServletRequest request) {
		System.out.println(" yy="+yy);
		System.out.println(" mm="+mm);
		Calendar cld = Calendar.getInstance();
		cld.set(Calendar.YEAR, new Integer(yy).intValue());
		cld.set(Calendar.MONTH, new Integer(mm).intValue());
        //用户信息
//		ResUserVO user = (ResUserVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		 return secScheduleService.changeMonthStyle(getLoginUser(request).getUserId(), cld.getTime());

	}

	/**处理这条消息是否符合提醒条件
	 *
	 * @param SecScheduleDO
	 */
	public SecScheduleDO tackleReminderTime(SecScheduleDO schDO) {
		List<SecScheduleDO> tempList = new ArrayList<SecScheduleDO>(0);
		tempList.add(schDO);
		// 如果加入的数据是当天日期则提醒
		List<SecScheduleDO> schDOList = secScheduleService.tackleRepeatCycle(tempList, new Date());

		if (schDOList.size() == 0) {
			return null;
		} else {
			SecScheduleDO sch = schDOList.get(0);
			Calendar cal = Calendar.getInstance();
			Calendar nowCal = Calendar.getInstance();
			nowCal.setTime(new Date());
			cal.setTime(sch.getStartTime());
		    cal.set(nowCal.get(Calendar.YEAR),nowCal.get(Calendar.MONTH),nowCal.get(Calendar.DAY_OF_MONTH));

		    //不提醒
			if ((cal.getTimeInMillis()<nowCal.getTimeInMillis())||sch.getRemindCycle().equals("25")) {
				return null;
			}
			//准时提醒

			// 提前15分钟
			if (sch.getRemindCycle().equals("27")) {
				cal.add(Calendar.MINUTE, -15);
			}

			// 提前30分钟
			if (sch.getRemindCycle().equals("28")) {
				cal.add(Calendar.MINUTE, -30);
			}

			// 提前1小时
			if (sch.getRemindCycle().equals("29")) {
				cal.add(Calendar.MINUTE, -60);
			}
			// 提前一天
			if (sch.getRemindCycle().equals("30")) {
				cal.add(Calendar.DATE, -1);
			}
			// 时间差
			Long timeGap = (cal.getTimeInMillis() - nowCal.getTimeInMillis()) / 1000;
			System.out.println(" timeGap=" +timeGap);
			if (timeGap > 0) {
				sch.setRemindTime(cal.getTime());
				sch.setTimeGap(timeGap);
				return sch;
			} else {
				return null;
			}
		}// else
	}

	public void setSecDictService(ISecDictService secDictService) {
		this.secDictService = secDictService;
	}

}
